package com.sdust.position.controller;

import com.sdust.feign.clients.UserFeignClient;
import com.sdust.model.common.Result;
import com.sdust.model.position.dtos.PositionDto;
import com.sdust.model.position.entity.Position;
import com.sdust.model.position.vos.PositionVo;
import com.sdust.position.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/service/position")
public class PositionController {

    @Autowired
    private PositionService positionService;

    @Autowired
    private UserFeignClient userFeignClient;

    /**
     * 保存位置信息
     * @param postionDto
     * @return
     */
    @PostMapping("/uploadPosition")
    public Result uploadPostion(@RequestBody PositionDto postionDto){

//        // 1. 验证Token
//        String userId = JwtUtil.parseToken(token.replace("Bearer ", ""));
//        if (userId == null) {
//            return ResponseEntity.status(401).body(ApiResponse.error("无效Token"));
//        }

        // 2. 保存位置数据
        Position position = new Position();
        position.setUserId("1");
        position.setLatitude(postionDto.getLatitude());
        position.setLongitude(postionDto.getLongitude());
        position.setTimestamp(LocalDateTime.now());

        positionService.savePosition(position);

        // 3. 返回成功响应
        return Result.success("位置上传成功");
    }


    /**
     * 获取附近的用户
     * @param latitude
     * @param longitude
     * @return
     */
    @GetMapping("/getNearbyUsers")
    public Result getNearbyLocations(@RequestParam Double latitude,@RequestParam Double longitude) {

//        // 1. 验证Token
//        String userId = JwtUtil.parseToken(token.replace("Bearer ", ""));
//        if (userId == null) {
//            return ResponseEntity.status(401).body(ApiResponse.error("无效Token"));
//        }

        // 2. 查询附近位置（示例：1公里范围内）
        List<PositionVo> nearbyLocations = positionService.getNearbyUsers(
                latitude,
                longitude,
                1000000000);

        // 3. 返回标准化响应
        return Result.success(nearbyLocations);
    }

    /**
     * 位置服务测试接口
     * @return
     */
    @GetMapping("/test")
    public String test(){
        return "test";
    }


    /**
     * 测试通过Openfeign远程调用用户服务
     * @param userName
     * @return
     */
    @GetMapping("/testUser")
    public Result testUser(@RequestParam String userName) {
        return Result.success(userFeignClient.testUser(userName));
    }
}